#!/usr/bin/python3
# 文件名：server.py

# 导入 socket、sys 模块
import sys,socket,os,re,time

def nmap_icmp():#调用nmap扫描腾讯oc网段的icmp,返回本网段能ping通的腾讯主机列表
    ip = ['113.215.3.64/26', '113.215.11.0/25', '113.215.11.128/25', '113.215.22.128/26','113.215.13.128/26']
    ipList=[]
    for x in ip:
        nmap=os.popen('/usr/bin/nmap -e eth0 -sP %s' % (x)).read()
        nmapRES=re.findall("\d+\.\d+\.\d+\.\d+",nmap)
        ipList.extend(nmapRES)
    return ipList


if __name__ == '__main__':
    #启动一个端口是9999的服务
    sk = socket.socket()
    sk.bind(("0.0.0.0", 9999))
    sk.listen(5)
    print("start")
    while True:
        conn, addr = sk.accept()#被访问并建立链接以后
        print(addr, "已连接")
        print("服务端正在检测")
        try:
            ipList = nmap_icmp()#调用nmap扫描腾讯oc网段的icmp，返回本网段可以
            print(ipList)
            print("检测完毕")
            with open("/var/www/html/ten100HW.txt","w") as f:#写到本地，让客户端来get,直接通过socket来传有时会丢失数据
                for x in ipList:
                    f.write(x+"\t")
            #send_data = "\t".join(ipList)
            conn.close()  # 跳出循环时结束通讯
        except:
            conn.close()
            break
    print("发生错误")
